/*
 *Copyright (c) 2024 Black Sesame Technologies
 *
 *Licensed under the Apache License, Version 2.0 (the "License");
 *you may not use this file except in compliance with the License.
 *You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 *Unless required by applicable law or agreed to in writing, software
 *distributed under the License is distributed on an "AS IS" BASIS,
 *WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *See the License for the specific language governing permissions and
 *limitations under the License.
*/

// #include <vsprintf.h>
#include <string.h>
#include <stdarg.h>
#include <stdio.h>
#include "printf.h"


extern void putc_user(unsigned char c);
extern unsigned char getc_user(void);

#define    OUTBUFSIZE    1024
#define    INBUFSIZE    1024


static unsigned char g_pcOutBuf[OUTBUFSIZE]={0};
static unsigned char g_pcInBuf[INBUFSIZE]={0};
static unsigned char g_pcOutBuf_intr[OUTBUFSIZE]={0};


volatile static int clsPrt = 0;

void closePrintf(void)
{
    clsPrt = 1;
}
void openPrintf(void)
{
    clsPrt = 0;
}

int printf(const char *fmt, ...)
{
    #ifdef UART_DEBUG_RT2
    int i;
    int len;
    va_list args;

    if (clsPrt)
        return 0;

    va_start(args, fmt);
    len = vsprintf((char *)g_pcOutBuf,fmt,args);
    va_end(args);
    for (i = 0; i < strlen((const char *)g_pcOutBuf); i++)
    {
        if ('\n' == g_pcOutBuf[i])
        {
             putc_user('\r');
        }
        putc_user(g_pcOutBuf[i]);
    }
    return len;
    #endif
}

int printf_intr(const char *fmt, ...)
{
    int i;
    int len;
    va_list args;


    va_start(args, fmt);
    len = vsprintf((char *)g_pcOutBuf_intr,fmt,args);
    va_end(args);
    for (i = 0; i < strlen((const char *)g_pcOutBuf_intr); i++)
    {
        if ('\n' == g_pcOutBuf_intr[i])
        {
             putc_user('\r');
        }
        putc_user(g_pcOutBuf_intr[i]);
    }
    return len;
}


int scanf(const char * fmt, ...)
{
    int i = 0;
    unsigned char c;
    va_list args;
    
    while(1)
    {
        c = getc_user();
        if((c == 0x0d) || (c == 0x0a))
        {
            g_pcInBuf[i] = '\0';
            break;
        }
        else
        {
            g_pcInBuf[i++] = c;
        }
    }
    
    va_start(args,fmt);
    i = vsscanf((const char *)g_pcInBuf,fmt,args);
    va_end(args);

    return i;
}


